package com.xinyue.center.controller;

import com.xinyue.center.common.GameCenterConfig;
import com.xinyue.center.common.GameCenterError;
import com.xinyue.center.common.ServerResponse;
import com.xinyue.center.dao.entity.Account;
import com.xinyue.center.messages.response.GameGatewayInfoMsg;
import com.xinyue.center.service.GameGatewayService;
import com.xinyue.center.service.IAccountService;
import com.xinyue.center.service.model.GameGatewayInfo;
import com.xinyue.game.auth.AccountToken;
import com.xinyue.game.auth.JWTUtil;
import com.xinyue.game.common.GameCommonConstants;
import com.xinyue.game.utils.RSAUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author 王广帅
 * @Date 2020/12/26 21:26
 */
@RestController
@RequestMapping("gameGateway")
public class GameGatewayController {
    private Logger logger = LoggerFactory.getLogger(GameGatewayController.class);

    @Autowired
    private IAccountService accountService;
    @Autowired
    private GameGatewayService gameGatewayService;
    @Autowired
    private GameCenterConfig gameCenterConfig;

    @PostMapping("selectGameGateway")
    public Object selectGameGateway(HttpServletRequest request)
            throws Exception {
        String userToken = request.getHeader(GameCommonConstants.USER_TOKEN);
        AccountToken accountToken = JWTUtil.getTokenContent(userToken, AccountToken.class);
        Account account = accountService.selectAccount(accountToken.getAccountId());
        if (account == null) {
            throw GameCenterError.ACCOUNT_NOT_EXIST.newException("{}", accountToken.getAccountId());
        }
        long playerId = accountToken.getPlayerId();
        GameGatewayInfo gameGatewayInfo = gameGatewayService.getGameGatewayInfo(playerId).orElse(null);
        if (gameGatewayInfo == null) {
            throw GameCenterError.NO_GAME_GATEWAY_INFO.newException();
        }
        GameGatewayInfoMsg gameGatewayInfoMsg = new GameGatewayInfoMsg(gameGatewayInfo.getId(), gameGatewayInfo.getIp(),
                gameGatewayInfo.getPort());
        Map<String, Object> keyPair = RSAUtils.genKeyPair();// 生成rsa的公钥和私钥
        byte[] publickKeyBytes = RSAUtils.getPublicKey(keyPair);// 获取公钥
        String publickKey = Base64Utils.encodeToString(publickKeyBytes);// 为了方便传输，对bytes数组进行一下base64编码
        accountToken.setPublicKey(publickKey);
        accountToken.setGatewayIp(gameGatewayInfo.getIp());
        accountToken.updateExpireDays(gameCenterConfig.getPlayerTokenExpire());
        String token = JWTUtil.createToken(accountToken);
        gameGatewayInfoMsg.setToken(token);
        byte[] privateKeyBytes = RSAUtils.getPrivateKey(keyPair);
        String privateKey = Base64Utils.encodeToString(privateKeyBytes);
        gameGatewayInfoMsg.setRsaPrivateKey(privateKey);// 给客户端返回私钥
        logger.debug("player {} 获取游戏网关信息成功：{}", playerId, gameGatewayInfoMsg);
        ServerResponse<GameGatewayInfoMsg> responseEntity = new ServerResponse<>(gameGatewayInfoMsg);
        return responseEntity;
    }
}
